package com.ddstation.crm.organization_structure.service;

import com.ddstation.crm.organization_structure.entity.DtInvsOrganizationStructureStaffEntity;
import com.ddstation.crm.organization_structure.mapper.DtInvsOrganizationStructureStaffMapper;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;

@Service @Lazy
public class StaffServiceImpl implements StaffService {

	@Override
	@Transactional(readOnly=true)
	public List<DtInvsOrganizationStructureStaffEntity> getCoverStaff(int orgId) {
		// TODO Auto-generated method stub
		return dtInvsOrganizationStructureStaffMapper.select(deptService.getCoverDept(orgId), null);
	}
	
	//add by zhengxb start 2018.4.9 start--------------------------
	@Override
	@Transactional(readOnly=true)
	public List<DtInvsOrganizationStructureStaffEntity> getCoverStaffByName(int orgId, String name) {
		return dtInvsOrganizationStructureStaffMapper.select(deptService.getCoverDept(orgId), name);
	}
	//add by zhengxb start 2018.4.9 end--------------------------
	
	@Override
	@Transactional(readOnly=true)
	public List<String> getBeManagedStaff(String institutionId, int doctorId) {
		// TODO Auto-generated method stub
		List<String> bemanaged = new ArrayList<String>();
		List<DtInvsOrganizationStructureStaffEntity> doctors = dtInvsOrganizationStructureStaffMapper.selectStaffInInstitution(institutionId, doctorId);
		if (doctors != null) {
			for (DtInvsOrganizationStructureStaffEntity doctor : doctors) {
				if (doctor.getIsManager().intValue() == 1) { // 管理员
					List<DtInvsOrganizationStructureStaffEntity> staffs = this.getCoverStaff(doctor.getOrg().getId());
					if (staffs != null) {
						for (DtInvsOrganizationStructureStaffEntity staff : staffs) {
							bemanaged.add(staff.getDoctor().getId());
						}
					}
				} else {
					if (!bemanaged.contains(doctor.getDoctor().getId())) {
						bemanaged.add(doctor.getDoctor().getId());
					}
				}
			}
		}
		return bemanaged;
	}
	
//	/**
//	 * 验证访问合法性
//	 * @param institutionId
//	 * @param orgId
//	 */
//	private boolean accessable(String institutionId, int orgId) {
//		DtInvsOrganizationStructureEntity dept = dtOrganizationStructureMapper.selectByPK(orgId);
//		if (dept == null) throw new IllegalStateException("组织架构不存在 orgId=" + orgId);
//		
//		if (!institutionId.equals(dept.getIntitutionId())) throw new IllegalStateException("组织架构不存在 orgId=" + orgId);
//		
//		return true;
//	}

	@Inject private OrgService deptService = null;
	@Inject private DtInvsOrganizationStructureStaffMapper dtInvsOrganizationStructureStaffMapper = null;
}
